<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>代理和反射-面试题</title>
</head>

<body>
  <script>
    /* 
      代理和反射-面试题
    */

    // 未锁定的情况下
    var people1 = {
      name: "strick"
    }

    var handler1 = {
      has(target, property) {
        if(property === "age") {
          return true
        }
        return property in target
      }
    }
    var p1 = new Proxy(people1, handler1)

    console.log("name" in p1)
    console.log("age" in p1)
    console.log("school" in p1)

    // 锁定的情况下
    var people2 = {
      name: "strick"
    }

    var handler2 = {
      has(target, property) {
        // return false
        return true
      }
    }
    Object.preventExtensions(people2)
    var p2 = new Proxy(people2, handler2)

    console.log("name" in p2)   // 报错 锁定的对象 用has拦截会报错  类型错误 并且是当且仅当 has()返回false时报错
    console.log("age" in p2)
    console.log("school" in p2)

    var people3 = {
      current: function() {
        return this === p3
      }
    }

    var p3 = new Proxy(people3, {})
    console.log(p3.current(), p3)

    var people4 = {
      name: "strick",
      age: 28,
      [Symbol.for("gender")]: "man",
      school: "university"
    }

    var handler4 = {
      ownKeys(target) {
        return Reflect.ownKeys(target).filter((value, index) => {
          return index % 2 == 0
        })
      }
    }

    var p4 = new Proxy(people4, handler4)
    console.log(Object.getOwnPropertyNames(p4))   // ['name', 'school'] 返回自有属性（不包括用符号表示的属性），然后再过滤掉奇数位置的属性
  </script>
</body>

</html>